'use strict'

const { ApiController } = require('jax')

class DemoArticleController extends ApiController {
  get Model() {
    return this.ctx.model.DemoArticle
  }

  // 批量查询
  get searchKey() {
    return ['isOpen', 'typeId']
  }

  // 模糊查询
  get searchKey() {
    return ['title']
  }

  // 列表查询前
  async beforeIndex() {
    const { ctx } = this
    const { query, helper } = ctx
    const where = {}

    ;['isOpen', 'storeId'].map((key) => {
      if (query[key] && !query[key] == '') where[key] = query[key]
    })

    if (query.keyword && !query.keyword == '') where.title = new RegExp(helper.toMongoRegex(query.keyword), 'i')

    // 开始时间
    if (query.startTime && query.startTime != '')
      where.createdAt = {
        $gte: query.startTime + ' 00:00:00',
      }

    // 结束时间
    if (query.endTime && query.endTime != '')
      where.createdAt = {
        ...where.createdAt,
        $lte: query.endTime + ' 23:59:59',
      }

    return {
      where,
      sort: {
        // 使用序号排序
        // isTop: 'DESC',
        // rank: 'ASC',

        // ID降序
        _id: 'DESC',
      },
    }
  }

  // 导出
  async exportConfig() {
    return [
      { name: '标题', key: 'title' },
      { name: '状态', key: 'isOpenDesc' },
      { name: '创建时间', key: 'createdAt' },
      { name: '描述', value: (item) => item.desc },
    ]
  }

  // 导入
  async importDevice() {
    const { ctx } = this
    const { config } = this
    const { url } = ctx.request.body

    const localFile = config.storageDir + URL.parse(url).path

    const workSheetsFromFile = xlsx.parse(localFile)
    if (workSheetsFromFile) {
      const data = workSheetsFromFile[0].data

      for (let i = 0; i < data.length; i++) {
        if (i == 0) continue

        const [name, mobile, company] = data[i]

        if (!mobile || mobile == '') continue

        await ctx.model.Staff.findOneAndUpdate(
          {
            // name,
            mobile,
          },
          {
            name,
            mobile,
            company,
            isOpen: true,
          },
          {
            upsert: true,
            new: true,
          }
        )

        await ctx.model.User.updateOne(
          {
            mobile,
          },
          {
            isStaff: 1,
          }
        )
      }
    }

    ctx.body = {
      code: 0,
      msg: '导入成功',
    }
  }
}

module.exports = DemoArticleController
